package com.majx.controller;

import com.majx.pojo.User;
import com.majx.service.Exception.UserExpetion;
import com.majx.service.UserService;
import com.majx.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    @Qualifier("UserService")
    private UserService userService;

    /**
     * 验证登录
     * @param loginUser
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public Map<String,Object> login(@RequestBody User loginUser) {
        Map<String,Object> res = new HashMap<String, Object>();
        Map<String,Object> data = new HashMap<String, Object>();
        Map<String,Object> meta = new HashMap<String, Object>();


        User user;
        try {
            user = userService.login(loginUser);
            String token = TokenUtil.sign(loginUser.getUsername());

            meta.put("msg","登录成功");
            meta.put("status","200");


            data.put("token",token);
            data.put("user",user);

        } catch (UserExpetion userExpetion) {
            data.put("user",null);
            data.put("token",null);

            meta.put("msg",userExpetion.getMessage());
            meta.put("status","0");
        }
        res.put("meta",meta);
        res.put("data",data);

        return res;
    }


    /**
     * 获取用户信息
     * @param uid
     * @return
     */
    @RequestMapping("/getUser")
    @ResponseBody
    public User getUser(@RequestParam("uid") Integer uid){
        return userService.getUser(uid);
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    public Integer updateUser(@RequestBody User user){
        System.out.println("user = "+user);
        return userService.updateUser(user);
    }

    /**
     * 获取用户总数
     * @return
     */
    @RequestMapping("/getUserCount")
    @ResponseBody
    public Integer getUserCount(){
        return userService.getUserCount();
    }
}
